﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Xml.Linq;
using System.Text.RegularExpressions;

namespace PhoneAppProject1
{
    public partial class Detail_News : PhoneApplicationPage
    {
        public Detail_News()
        {
            InitializeComponent();
        }

        private void GetData()
        {
			myProgress.IsIndeterminate = !myProgress.IsIndeterminate;
            myProgress.Visibility = System.Windows.Visibility.Visible;
            string URL = ""; string Title = "";
            NavigationContext.QueryString.TryGetValue("URL", out URL);
            NavigationContext.QueryString.TryGetValue("Title", out Title);
            WebClient webClientObj = new WebClient();
            webClientObj.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClientObj_DownloadStringCompleted);
            //webClientObj.DownloadStringAsync(new Uri("http://rssfeeds.sanook.com/rss/feeds/sanook/game.hit.xml", UriKind.RelativeOrAbsolute));
            //webClientObj.DownloadStringAsync(new Uri("http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/football/rss.xml", UriKind.RelativeOrAbsolute));
            webClientObj.DownloadStringAsync(new Uri(URL, UriKind.RelativeOrAbsolute));
            PageTitle.Text = Title;
            // TODO: Add event handler implementation here.
        }

        private void PhoneApplicationPage_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            this.GetData();
            //string URL = ""; string Title = "";
            //NavigationContext.QueryString.TryGetValue("URL", out URL);
            //NavigationContext.QueryString.TryGetValue("Title", out Title);
            //WebClient webClientObj = new WebClient();
            //webClientObj.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClientObj_DownloadStringCompleted);
            ////webClientObj.DownloadStringAsync(new Uri("http://rssfeeds.sanook.com/rss/feeds/sanook/game.hit.xml", UriKind.RelativeOrAbsolute));
            ////webClientObj.DownloadStringAsync(new Uri("http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/football/rss.xml", UriKind.RelativeOrAbsolute));
            //webClientObj.DownloadStringAsync(new Uri(URL, UriKind.RelativeOrAbsolute));
            //PageTitle.Text = Title;
        	// TODO: Add event handler implementation here.
			
        }

        void webClientObj_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                ListItem.SelectionChanged -= new SelectionChangedEventHandler(ListItem_SelectionChanged);
                ListItem.Visibility = System.Windows.Visibility.Collapsed;

                string str = e.Result.Replace("media:thumbnail", "XmllImage");
                XElement twitterObj = XElement.Parse(str);
                //XElement tempElementImage = twitterObj.Descendants(XName.Get("channel")).FirstOrDefault();
                //XElement tempElementItem = tempElementImage.Descendants(XName.Get("item")).FirstOrDefault();
                //XNamespace media = "media";
                //XElement tempElementImageURL = tempElementItem.Descendants(media + "thumbnail").FirstOrDefault();


                var Objv = from Obj in twitterObj.Descendants("channel")
                           from ObjIn in Obj.Descendants("item")

                           select new XMLPaser
                           {
							 Title = ObjIn.Element("title").Value,
                               //Title = ObjIn.Element("title").Value.Replace("<![CDATA[", String.Empty).Replace("]]", String.Empty),
							   Link = ObjIn.Element("guid").Value,
                               DetailAll = Regex.Replace(ObjIn.Element("description").Value, @"<[^>]*>", String.Empty),
                               //Title = ObjIn.Element("title").Value.Replace("<![CDATA[", String.Empty).Replace("]]", String.Empty),
                               ImageURL = CheckImage(ObjIn),
                               CreateDate = Convert.ToDateTime(ObjIn.Element("pubDate").Value).ToString("dd, dddd MMMM yyyy"),
                               Message = this.CutDescription(Regex.Replace(ObjIn.Element("description").Value, @"<[^>]*>", String.Empty).ToString())
                           };

                ListItem.ItemsSource = Objv;
                myProgress.IsIndeterminate = !myProgress.IsIndeterminate;

                myProgress.Visibility = System.Windows.Visibility.Collapsed;
                ListItem.Visibility = System.Windows.Visibility.Visible;
                ListItem.SelectionChanged += new SelectionChangedEventHandler(ListItem_SelectionChanged);
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
                //ListItem.SelectionChanged -= new SelectionChangedEventHandler(ListItem_SelectionChanged);

            }
        }

        private string CheckImage(XElement ObjIn)
        {
            string ImageUrl = "";
            try
            {
                ImageUrl = ObjIn.Element("XmllImage").Attribute("url").Value;
                string[] image = ImageUrl.Split('.');

                if (image[image.Length - 1] == "gif")
                {
                    ImageUrl = "Nopicture.png";
                }
                else if (ImageUrl == "" || ImageUrl == null)
                {
                    ImageUrl = "Nopicture.png";
                }
            }
            catch
            {
                ImageUrl = "Nopicture.png";
            }
            return ImageUrl;
        }

        private string CutDescription(string Objstring)
        {
            if (Objstring.Length > 60)
            {
                Objstring = Objstring.Substring(0, 60) + " ...";
                return Objstring;
            }
            else
            {
                return Objstring;
            }

        }

        private void ListItem_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
        	// TODO: Add event handler implementation here.
			            XMLPaser Objv = (XMLPaser)ListItem.SelectedValue;

            string URL = Objv.Link;
            NavigationService.Navigate(new Uri("/SNews_Detail.xaml?URL= " + Objv.Link + 
                                               "&Message=" + Objv.DetailAll + ""+
                                               "&Title=" + Objv.Title + ""+
                                               "&CreateDate=" + Objv.CreateDate + ""+
                                                "&ImgURL=" + Objv.ImageURL + "",
                                                UriKind.RelativeOrAbsolute));
        }

        private void btnRefresh_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            ListItem.SelectionChanged -= new SelectionChangedEventHandler(ListItem_SelectionChanged);
            ListItem.ItemsSource = null;
            this.GetData();
        	// TODO: Add event handler implementation here.
        }

    }
}
